import 'package:flutter_menu/res/app_design.dart' hide SearchController;
import 'package:flutter_menu/widgets/load_container.dart';
import 'package:get/get.dart';
import './search_controller.dart';

class SearchPg extends GetView<SearchController> {
  final SearchController _controller = SearchController();

  SearchPg({super.key});

  static const normalTextColor = Color(0xff4F4F4F);
  static const highLightTextColor = AppColors.itemHighLight;

  @override
  SearchController get controller => _controller;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SearchController>(
        init: controller,
        builder: (controller) => body(context).whitScaffold());
  }

  Widget body(BuildContext context) {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      _searchBar(),
      Text(
        "search_title_dishes".tr,
        style: TextStyle(fontSize: AppDimen.sp_25),
      ).marginOnly(left: 27.w, top: 20.w),
      _searchResult().expanded(),
    ]).size(width: double.infinity);
  }

  Widget _searchResult() {
    return LoadContainer(
        controller: controller.loadSearchResultController!,
        emptyMessage: "orderSearchNoData".tr,
        child: Obx(() {
          return ListView.builder(
              itemCount: controller.dishResultList.length,
              itemBuilder: (context, index) {
                var dishModel = controller.dishResultList.value[index];
                return InkWell(
                    onTap: () {
                      controller.onItemClick(dishModel);
                    },
                    highlightColor: highLightTextColor,
                    child: _searchItem(dishModel.imageName ?? "",
                        dishModel.getLowestPrice().toString() ?? ""));
              });
        }));
  }

  Widget _searchBar() {
    var result = Container(
      height: 77.h,
      width: double.infinity,
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        border: Border.all(
          width: 2.h,
          color: AppColors.bgTab,
        ), // 边框
        color: AppColors.bgContainer, // 背景颜色
      ),
      padding: EdgeInsets.symmetric(horizontal: 17.w, vertical: 5.w),
      child: Row(
        children: [
          TextField(
            onChanged: (v) {
              controller.updateSearchQuery(v);
            },
            style: TextStyle(fontSize: AppDimen.sp_25),
            maxLength: 64,
            controller: controller.textFieldController,
            decoration: InputDecoration(
                hintStyle: const TextStyle(color: AppColors.text_666),
                hintText: "search_hint".tr,
                counterText: "",
                border: const OutlineInputBorder(borderSide: BorderSide.none),
                contentPadding: const EdgeInsets.only(
                    left: 4, top: 0, bottom: 0, right: 0)),
          ).expanded(),
          Obx(() {
            return ElevatedButton(
                onPressed: controller.isInputEmpty() ? null : controller.search,
                style: AppStyle.app_btn.copyWith(backgroundColor:
                    WidgetStateProperty.resolveWith<Color>(
                        (Set<WidgetState> states) {
                  if (states.contains(WidgetState.disabled)) {
                    return AppColors.text_999999;
                  }
                  return const Color(
                      0xff4a230a); // Use the component's default.
                })),
                child: Text(
                  "search_btn".tr,
                  style:
                      TextStyle(fontSize: AppDimen.sp_25, color: Colors.white),
                )).size(width: 134.w, height: double.infinity);
          })
        ],
      ),
    );
    return result;
  }

  Widget _searchItem(String title, String price) {
    var searchQuery = controller.searchQuery.value;
    return Container(
      height: 64.w,
      padding: EdgeInsets.symmetric(horizontal: 27.w),
      child: Row(
        children: [
          RichText(
            text: TextSpan(
              children: _highlightSearchResult(title, searchQuery),
            ),
          ).size(width: 506.w),
          Text(
            price,
            textAlign: TextAlign.end,
              style: TextStyle(
                  fontSize: AppDimen.sp_24,
                  overflow: TextOverflow.ellipsis,
                  color: normalTextColor)
          ).expanded(),
        ],
      ).center(),
    );
  }

  List<TextSpan> _highlightSearchResult(String text, String query) {
    if (query.isEmpty) {
      return [TextSpan(text: text)];
    }

    final regex = RegExp('($query)', caseSensitive: false);
    final matches = regex.allMatches(text);
    int lastMatchEnd = 0;

    List<TextSpan> spans = [];

    for (final match in matches) {
      // Add the text before the match
      if (match.start > lastMatchEnd) {
        spans.add(TextSpan(
          text: text.substring(lastMatchEnd, match.start),
          style: TextStyle(
              fontSize: AppDimen.sp_24,
              overflow: TextOverflow.ellipsis,
              color: normalTextColor),
        ));
      }
      // Add the matched text
      spans.add(TextSpan(
        text: match.group(0),
        style: TextStyle(
            fontSize: AppDimen.sp_24,
            overflow: TextOverflow.ellipsis,
            color: normalTextColor,
            backgroundColor: highLightTextColor),
      ));
      lastMatchEnd = match.end;
    }

    // Add any remaining text after the last match
    if (lastMatchEnd < text.length) {
      spans.add(TextSpan(
        text: text.substring(lastMatchEnd),
        style: TextStyle(
            fontSize: AppDimen.sp_24,
            overflow: TextOverflow.ellipsis,
            color: normalTextColor),
      ));
    }

    return spans;
  }
}
